
//
//  VIPIMChatroomManager.m
//  TTProduct
//
//  Created by My mac on 2019/8/5.
//  Copyright © 2019年 TTProduct. All rights reserved.
//

#import "VIPIMChatroomManager.h"
#import "VIPPCH.h"

@interface VIPIMChatroomManager () <NIMChatroomManagerDelegate>

@property (weak, nonatomic) id<NIMChatroomManager> chatroomManager;

@end

@implementation VIPIMChatroomManager

#pragma mark <NIMChatroomManagerDelegate>
// 互踢回调
- (void)chatroomBeKicked:(NIMChatroomBeKickedResult *)result {
    if (self.loginedLostConnection == nil) return;
    VIPMessage *message = [self messageWithEcode:result.reason];
    self.loginedLostConnection(message);
}

- (void)joinRoomCompletion:(VIPCompletionHandler)completion {
    WS(weakSelf)
    NIMChatroomEnterRequest *request = [NIMChatroomEnterRequest new];
    request.roomId = self.signal.roomId;
    [_chatroomManager enterChatroom:request completion:^(NSError * _Nullable error, NIMChatroom * _Nullable chatroom, NIMChatroomMember * _Nullable me) {
        weakSelf.status = VIPSignalStateLoginOK;
        if (!completion) return;
        VIPMessage *message = [weakSelf messageWithEcode:error.code];
        completion(message);
    }];
}

- (void)sendMessageCompletion:(VIPCompletionHandler)completion {
    NSError *error = nil;
    [self sendMessageType:NIMSessionTypeChatroom error:&error];
    VIPMessage *message = [self messageWithEcode:error.code];
    if (!completion) return;
    completion(message);
}

- (void)leaveRoomCompletion:(VIPCompletionHandler)completion {
    WS(weakSelf)
    [self.chatroomManager exitChatroom:self.signal.roomId completion:^(NSError * _Nullable error) {
        if (!completion) return;
        VIPMessage *message = [weakSelf messageWithEcode:error.code];
        completion(message);
    }];
}

- (void)setupIM {
    [super setupIM];
    _chatroomManager = [self.nimSDK chatroomManager];
    [_chatroomManager addDelegate:self]; 
}

static VIPIMChatroomManager* _instance = nil;
+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:NULL] init];
        [_instance setupIM];
    });
    return _instance ;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    return [VIPIMChatroomManager shareManager];
}

- (id)copyWithZone:(struct _NSZone *)zone {
    return [VIPIMChatroomManager shareManager];
}

- (NSString *)signaingName {
    return @"网易 聊天室";
}
@end
